<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>友元声明</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/friend","wgTitle":"cpp/language/friend","wgCurRevisionId":64193,"wgArticleId":2716,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/friend","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_friend skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">友元声明</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em;">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="https://zh.cppreference.com/w/cpp/container" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="classes.html" title="cpp/language/classes">类</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="">
<tr class="t-nv-h2"><td colspan="5">概述</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="classes.html" title="cpp/language/classes">综述</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="class.html" title="cpp/language/class"><code>class</code>/<code>struct</code> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="union.html" title="cpp/language/union"><code>union</code> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="injected-class-name.html" title="cpp/language/injected-class-name">注入类名</a> </td></tr>
<tr class="t-nv-h2"><td colspan="5">成员</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html" title="cpp/language/data members">数据成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="static.html" title="cpp/language/static">静态成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="this.html" title="cpp/language/this"><code>this</code> 指针</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="nested_classes.html" title="cpp/language/nested types">嵌套类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_template.html" title="cpp/language/member template">成员模板</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="bit_field.html" title="cpp/language/bit field">位域</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="using_declaration.html" title="cpp/language/using declaration"><code>using</code> 声明</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_functions.html" title="cpp/language/member functions">成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="access.html" title="cpp/language/access">成员访问指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="constructor.html" title="cpp/language/initializer list">构造函数与成员初始化器列表</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">默认成员初始化器</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink"><code>friend</code> 指定符</strong></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="explicit.html" title="cpp/language/explicit"><code>explicit</code> 指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="converting_constructor.html" title="cpp/language/converting constructor">转换构造函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">特殊成员函数</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="default_constructor.html" title="cpp/language/default constructor">默认构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_constructor.html" title="cpp/language/copy constructor">复制构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_constructor.html" title="cpp/language/move constructor">移动构造函数</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_assignment.html" title="cpp/language/copy assignment">复制赋值运算符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_assignment.html" title="cpp/language/move assignment">移动赋值运算符</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="destructor.html" title="cpp/language/destructor">析构函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">继承</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="derived_class.html" title="cpp/language/derived class">基与派生类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="ebo.html" title="cpp/language/ebo">空基类优化</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="virtual.html" title="cpp/language/virtual">虚成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="abstract_class.html" title="cpp/language/abstract class">纯虚函数与抽象类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="override.html" title="cpp/language/override"><tt>override</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="final.html" title="cpp/language/final"><tt>final</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>友元声明出现于<a href="class.html" title="cpp/language/class">类体</a>内，并向一个函数或另一个类授予对包含友元声明的类的私有及受保护成员的访问权。
</p>
<h3><span class="mw-headline" id=".E8.AF.AD.E6.B3.95">语法</span></h3>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">friend</span></span></span> <span class="t-spar">函数声明</span>
</td>
<td> (1)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">friend</span></span></span> <span class="t-spar">函数定义</span>
</td>
<td> (2)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">friend</span></span></span> <span class="t-spar">详述类说明符</span> <code><b>;</b></code>
</td>
<td> (3)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">friend</span></span></span> <span class="t-spar">简单类型说明符</span> <code><b>;</b></code>
<p><span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">friend</span></span></span> <span class="t-spar">typename-说明符</span> <code><b>;</b></code>
</p>
</td>
<td> (4)
</td>
<td> <span class="t-mark-rev t-since-cxx11">(C++11 起)</span>
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<h3><span class="mw-headline" id=".E6.8F.8F.E8.BF.B0">描述</span></h3>
<div class="t-li1"><span class="t-li">1)</span> 指明一个或数个函数为此类的友元
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> Y <span class="br0">{</span>
    <span class="kw4">int</span> data<span class="sy4">;</span> <span class="co1">// 私有成员</span>
    <span class="co1">// 非成员函数的运算符 operator&lt;&lt; 将拥有对 Y 的私有成员的访问权</span>
    <span class="kw1">friend</span> <a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> out, <span class="kw4">const</span> Y<span class="sy3">&amp;</span> o<span class="br0">)</span><span class="sy4">;</span>
    <span class="kw1">friend</span> <span class="kw4">char</span><span class="sy2">*</span> X<span class="sy4">::</span><span class="me2">foo</span><span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 其他类的成员亦可为友元</span>
    <span class="kw1">friend</span> X<span class="sy4">::</span><span class="me2">X</span><span class="br0">(</span><span class="kw4">char</span><span class="br0">)</span>, X<span class="sy4">::</span>~X<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 构造函数与析构函数亦可为友元</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 友元声明不声明成员函数</span>
<span class="co1">// 此 operator&lt;&lt; 仍需定义，作为非成员</span>
<a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> out, <span class="kw4">const</span> Y<span class="sy3">&amp;</span> y<span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">return</span> out <span class="sy1">&lt;&lt;</span> y.<span class="me1">data</span><span class="sy4">;</span> <span class="co1">// 可访问私有成员 Y::data</span>
<span class="br0">}</span></pre></div></div></div>
<div class="t-li1"><span class="t-li">2)</span> （只允许在非<a href="class.html#.E5.B1.80.E9.83.A8.E7.B1.BB" title="cpp/language/class">局部</a>类的定义中使用）定义一个非成员函数，同时令其为此类的友元。这种非成员函数始终为<a href="inline.html" title="cpp/language/inline">内联函数</a>。
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> X <span class="br0">{</span>
    <span class="kw4">int</span> a<span class="sy4">;</span>
    <span class="kw1">friend</span> <span class="kw4">void</span> friend_set<span class="br0">(</span>X<span class="sy3">&amp;</span> p, <span class="kw4">int</span> i<span class="br0">)</span> <span class="br0">{</span>
        p.<span class="me1">a</span> <span class="sy1">=</span> i<span class="sy4">;</span> <span class="co1">// 此为非成员函数</span>
    <span class="br0">}</span>
 <span class="kw1">public</span><span class="sy4">:</span>
    <span class="kw4">void</span> member_set<span class="br0">(</span><span class="kw4">int</span> i<span class="br0">)</span> <span class="br0">{</span>
        a <span class="sy1">=</span> i<span class="sy4">;</span> <span class="co1">// 此为成员函数</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div></div>
<div class="t-li1"><span class="t-li">3)</span> 指定以 <span class="t-spar">详述类说明符</span>（见<a href="elaborated_type_specifier.html" title="cpp/language/elaborated type specifier">详述类型说明符</a>）指名的 class、struct 或 union 为此类的友元。这意味着，该友元的各成员声明和定义可以访问此类的私有与受保护成员，而且该友元也能从此类的私有或受保护成员进行继承。
不需要提前声明用于此友元声明的类名。</div>
<div class="t-li1"><span class="t-li">4)</span> 指定以 <span class="t-spar">简单类型说明符</span> 或 <span class="t-spar">typename-说明符</span> 指名的类型，若该类型是（可有 <a href="cv.html" title="cpp/language/cv">cv 限定</a>的）class、struct 或 union，则为此类的友元；否则忽略该 <code>friend</code> 声明。此声明不前置声明新类型。
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> Y <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> A <span class="br0">{</span>
    <span class="kw4">int</span> data<span class="sy4">;</span> <span class="co1">// 私有数据成员</span>
    <span class="kw1">class</span> B <span class="br0">{</span> <span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 私有嵌套类型</span>
    <span class="kw2">enum</span> <span class="br0">{</span> a <span class="sy1">=</span> <span class="nu0">100</span> <span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 私有枚举项</span>
    <span class="kw1">friend</span> <span class="kw1">class</span> X<span class="sy4">;</span> <span class="co1">// 友元类的前置声明（详述类型说明符）</span>
    <span class="kw1">friend</span> Y<span class="sy4">;</span> <span class="co1">// 友元类声明（简单类型说明符） (C++11 起)</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw1">class</span> X <span class="sy4">:</span> A<span class="sy4">::</span><span class="me2">B</span> <span class="co1">// OK：友元能访问 A::B</span>
<span class="br0">{</span>
    A<span class="sy4">::</span><span class="me2">B</span> mx<span class="sy4">;</span> <span class="co1">// OK：友元的成员能访问 A::B</span>
    <span class="kw1">class</span> Y <span class="br0">{</span>
        A<span class="sy4">::</span><span class="me2">B</span> my<span class="sy4">;</span> <span class="co1">// OK：友元的嵌套成员能访问 A::B</span>
    <span class="br0">}</span><span class="sy4">;</span>
    <span class="kw4">int</span> v<span class="br0">[</span>A<span class="sy4">::</span><span class="me2">a</span><span class="br0">]</span><span class="sy4">;</span> <span class="co1">// OK：友元的成员能访问 A::a</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div></div>
<h3><span class="mw-headline" id=".E6.B3.A8.E8.A7.A3">注解</span></h3>
<p>友元关系不传递（你朋友的朋友不是你的朋友）。
</p><p>友元关系不继承（你朋友的孩子不是你的朋友）。
</p><p>友元函数声明中不允许使用存储类说明符。在友元声明中定义的函数具有外部连接，先前已定义的函数保持其定义时所具有的连接。
</p><p><a href="access.html" title="cpp/language/access">访问说明符</a>对于友元声明的含义没有影响（它们可出现于 <code>private:</code> 或于 <code>public:</code> 节，且并无区别）
</p><p>友元类声明不能定义新的类（<span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw1">friend</span> <span class="kw1">class</span> X <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span></span></span> 是错的）
</p><p>当局部类将一个无限定的函数或类声明为其友元时，只<a href="lookup.html" title="cpp/language/lookup">查找</a>在其最内层非类作用域中的函数与类，而非全局函数：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> F <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw4">extern</span> <span class="kw4">int</span> g<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
    <span class="kw1">class</span> Local <span class="br0">{</span> <span class="co1">// main() 函数中的局部类</span>
        <span class="kw1">friend</span> <span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 错误，没有声明于 main() 的该函数</span>
        <span class="kw1">friend</span> <span class="kw4">int</span> g<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// OK，main() 中有 g 的声明</span>
        <span class="kw1">friend</span> <span class="kw1">class</span> F<span class="sy4">;</span> <span class="co1">// 令局部 F（随后定义）为友元</span>
        <span class="kw1">friend</span> <span class="kw1">class</span> <span class="sy4">::</span><span class="me2">F</span><span class="sy4">;</span> <span class="co1">// 令全局 F 为友元</span>
    <span class="br0">}</span><span class="sy4">;</span>
    <span class="kw1">class</span> F <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 局部 F</span>
<span class="br0">}</span></pre></div></div>
<p>在类或类模板 X 中的友元声明中被首次声明的名字，成为 X 的最内层外围命名空间的成员，但对于查找不可见（除了考虑 X 的<a href="adl.html" title="cpp/language/adl">实参依赖查找</a>），除非在该命名空间作用域中提供与之匹配的声明——细节见<a href="namespace.html#.E5.91.BD.E5.90.8D.E7.A9.BA.E9.97.B4" title="cpp/language/namespace">命名空间</a>。
</p>
<h3><span class="mw-headline" id=".E6.A8.A1.E6.9D.BF.E5.8F.8B.E5.85.83">模板友元</span></h3>
<p><a href="function_template.html" title="cpp/language/function template">函数模板</a>与<a href="class_template.html" title="cpp/language/class template">类模板</a>声明，都可带 <code>friend</code> 说明符出现于任何非局部类或类模板内（尽管只有函数模板能在授予友元关系的类或类模板内进行定义）。这种情况下，该模板的每个特化都成为友元，不管是被隐式实例化、部分特化或显式特化。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">class</span> A <span class="br0">{</span>
    <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> T<span class="sy1">&gt;</span>
    <span class="kw1">friend</span> <span class="kw1">class</span> B<span class="sy4">;</span> <span class="co1">// 每个 B&lt;T&gt; 都是 A 的友元</span>
 
    <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> T<span class="sy1">&gt;</span>
    <span class="kw1">friend</span> <span class="kw4">void</span> f<span class="br0">(</span>T<span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span> <span class="co1">// 每个 f&lt;T&gt; 都是 A 的友元</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>友元声明不能指代部分特化，但能指代全特化：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span> <span class="kw1">class</span> A <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 主模板</span>
<span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span> <span class="kw1">class</span> A<span class="sy1">&lt;</span>T<span class="sy2">*</span><span class="sy1">&gt;</span> <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 部分特化</span>
<span class="kw1">template</span><span class="sy1">&lt;&gt;</span> <span class="kw1">class</span> A<span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span> <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 全特化</span>
<span class="kw1">class</span> X <span class="br0">{</span>
    <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span> <span class="kw1">friend</span> <span class="kw1">class</span> A<span class="sy1">&lt;</span>T<span class="sy2">*</span><span class="sy1">&gt;</span><span class="sy4">;</span> <span class="co1">// 错误！</span>
    <span class="kw1">friend</span> <span class="kw1">class</span> A<span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span><span class="sy4">;</span> <span class="co1">// OK</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>当友元声明指代函数模板的全特化时，不能使用关键词 <code>inline</code> 和默认实参。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span> <span class="kw4">void</span> f<span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="sy4">;</span>
<span class="kw1">template</span><span class="sy1">&lt;&gt;</span> <span class="kw4">void</span> f<span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span><span class="br0">(</span><span class="kw4">int</span><span class="br0">)</span><span class="sy4">;</span>
 
<span class="kw1">class</span> X <span class="br0">{</span>
    <span class="kw1">friend</span> <span class="kw4">void</span> f<span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span><span class="br0">(</span><span class="kw4">int</span> x <span class="sy1">=</span> <span class="nu0">1</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 错误：不允许默认实参</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>模板友元声明可以指名类模板 A 的成员，它可以是成员函数或成员类型（类型必须用<a href="elaborated_type_specifier.html" title="cpp/language/elaborated type specifier">详述类型说明符</a>）。这种声明，仅当其 <span class="t-spar">嵌套名说明符</span> 中的最后组分（最后的 <code><b>::</b></code> 左边的名字）是一个指名该类模板的 <span class="t-spar">简单模板标识</span>（模板名后随角括号包围的实参列表）时，才是良构的。这种模板友元声明的模板形参必须可从该 <span class="t-spar">简单模板标识</span> 推导。
</p><p>此情况下，A 的任何特化的成员都成为友元。这不并涉及对主模板 A 的实例化：仅有的要求是从该特化推导 A 的模板形参成功，以及将推导出的模板实参替换到友元声明中所产生的声明，是该特化的成员的合法声明：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co1">// 主模板</span>
<span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span>
<span class="kw1">struct</span> A <span class="br0">{</span> 
  <span class="kw1">struct</span> B <span class="br0">{</span> <span class="br0">}</span><span class="sy4">;</span>
  <span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
  <span class="kw1">struct</span> D <span class="br0">{</span> <span class="kw4">void</span> g<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
  T h<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
  <span class="kw1">template</span><span class="sy1">&lt;</span>T U<span class="sy1">&gt;</span> T i<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 全特化</span>
<span class="kw1">template</span><span class="sy1">&lt;&gt;</span>
<span class="kw1">struct</span> A<span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span> <span class="br0">{</span>
  <span class="kw1">struct</span> B <span class="br0">{</span> <span class="br0">}</span><span class="sy4">;</span>
  <span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
  <span class="kw1">struct</span> D <span class="br0">{</span> <span class="kw4">void</span> g<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
  <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw4">int</span> U<span class="sy1">&gt;</span> <span class="kw4">int</span> i<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 另一全特化</span>
<span class="kw1">template</span><span class="sy1">&lt;&gt;</span>
<span class="kw1">struct</span> A<span class="sy1">&lt;</span><span class="kw4">float</span><span class="sy2">*</span><span class="sy1">&gt;</span> <span class="br0">{</span>
    <span class="kw4">int</span> <span class="sy2">*</span>h<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 非模板类向类模板 A 的成员授予友元关系</span>
<span class="kw1">class</span> X <span class="br0">{</span>
  <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span>
  <span class="kw1">friend</span> <span class="kw1">struct</span> A<span class="sy1">&lt;</span>T<span class="sy1">&gt;</span><span class="sy4">::</span><span class="me2">B</span><span class="sy4">;</span> <span class="co1">// 所有的 A&lt;T&gt;::B 都是友元，包括 A&lt;int&gt;::B</span>
 
  <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span>
  <span class="kw1">friend</span> <span class="kw4">void</span> A<span class="sy1">&lt;</span>T<span class="sy1">&gt;</span><span class="sy4">::</span><span class="me2">f</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>  <span class="co1">// A&lt;int&gt;::f() 不是友元，因为其签名不匹配，</span>
                          <span class="co1">// 但比如 A&lt;char&gt;::f() 则是友元</span>
 
<span class="co1">//  template&lt;class T&gt;</span>
<span class="co1">//  friend void A&lt;T&gt;::D::g(); // 非良构：嵌套名说明符的最后部分，</span>
<span class="co1">//                            // A&lt;T&gt;::D:: 中 的 D，不是简单模板标识</span>
 
  <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span>
  <span class="kw1">friend</span> <span class="kw4">int</span><span class="sy2">*</span> A<span class="sy1">&lt;</span>T<span class="sy2">*</span><span class="sy1">&gt;</span><span class="sy4">::</span><span class="me2">h</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>  <span class="co1">// 所有 A&lt;T*&gt;::h 都是友元：A&lt;float*&gt;::h()、A&lt;int*&gt;::h() 等等</span>
 
  <span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">class</span> T<span class="sy1">&gt;</span> 
  <span class="kw1">template</span><span class="sy1">&lt;</span>T U<span class="sy1">&gt;</span>       <span class="co1">// A&lt;T&gt;::i() 的所有实例化和 A&lt;int&gt;::i() 都是友元，</span>
  <span class="kw1">friend</span> T A<span class="sy1">&lt;</span>T<span class="sy1">&gt;</span><span class="sy4">::</span><span class="me2">i</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 从而这些函数模板的所有特化都是</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx11"><td>
<p>模板友元声明中允许使用<a href="template_parameters.html#.E9.BB.98.E8.AE.A4.E6.A8.A1.E6.9D.BF.E5.AE.9E.E5.8F.82" title="cpp/language/template parameters">默认模板实参</a>，但仅当该声明是定义且此翻译单元不出现此函数模板的其他声明时才允许。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
</table>
<h3><span class="mw-headline" id=".E6.A8.A1.E6.9D.BF.E5.8F.8B.E5.85.83.E8.BF.90.E7.AE.97.E7.AC.A6">模板友元运算符</span></h3>
<p>模板友元的一种常见使用场合是作用于类模板上的非成员运算符重载的声明，例如针对某个用户定义的 <span class="t-c"><span class="mw-geshi cpp source-cpp">Foo<span class="sy1">&lt;</span>T<span class="sy1">&gt;</span></span></span> 的 <span class="t-c"><span class="mw-geshi cpp source-cpp">operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span>, <span class="kw4">const</span> Foo<span class="sy1">&lt;</span>T<span class="sy1">&gt;</span><span class="sy3">&amp;</span><span class="br0">)</span></span></span>
</p><p>这种运算符可在类体内定义，其效果是对每个 <code>T</code> 生成独立的非模板 <code>operator&lt;&lt;</code>，并使该非模板 <code>operator&lt;&lt;</code> 为其 <code>Foo&lt;T&gt;</code> 的友元
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
 
<span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> T<span class="sy1">&gt;</span>
<span class="kw1">class</span> Foo <span class="br0">{</span>
 <span class="kw1">public</span><span class="sy4">:</span>
    Foo<span class="br0">(</span><span class="kw4">const</span> T<span class="sy3">&amp;</span> val<span class="br0">)</span> <span class="sy4">:</span> data<span class="br0">(</span>val<span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span>
 <span class="kw1">private</span><span class="sy4">:</span>
    T data<span class="sy4">;</span>
 
    <span class="co1">// 为这个 T 生成非模板 operator&lt;&lt; </span>
    <span class="kw1">friend</span> <a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> os, <span class="kw4">const</span> Foo<span class="sy3">&amp;</span> obj<span class="br0">)</span>
    <span class="br0">{</span>
        <span class="kw1">return</span> os <span class="sy1">&lt;&lt;</span> obj.<span class="me1">data</span><span class="sy4">;</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    Foo<span class="sy1">&lt;</span><span class="kw4">double</span><span class="sy1">&gt;</span> obj<span class="br0">(</span><span class="nu16">1.23</span><span class="br0">)</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> obj <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">1.23</pre></div></div> 
</div>
<p>否则，函数模板不得不在类体之前声明为模板，这种情况下 <code>Foo&lt;T&gt;</code> 内的友元声明可以涉指 <code>operator&lt;&lt;</code> 对其 <code>T</code> 的全特化：
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
 
<span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> T<span class="sy1">&gt;</span>
<span class="kw1">class</span> Foo<span class="sy4">;</span> <span class="co1">// 前置声明，以令函数声明可行</span>
 
<span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> T<span class="sy1">&gt;</span> <span class="co1">// 声明</span>
<a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span>, <span class="kw4">const</span> Foo<span class="sy1">&lt;</span>T<span class="sy1">&gt;</span><span class="sy3">&amp;</span><span class="br0">)</span><span class="sy4">;</span>
 
<span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> T<span class="sy1">&gt;</span>
<span class="kw1">class</span> Foo <span class="br0">{</span>
 <span class="kw1">public</span><span class="sy4">:</span>
    Foo<span class="br0">(</span><span class="kw4">const</span> T<span class="sy3">&amp;</span> val<span class="br0">)</span> <span class="sy4">:</span> data<span class="br0">(</span>val<span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span>
 <span class="kw1">private</span><span class="sy4">:</span>
    T data<span class="sy4">;</span>
 
    <span class="co1">// 涉指对于这个特定的 T 的全特化 </span>
    <span class="kw1">friend</span> <a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span> <span class="sy1">&lt;&gt;</span> <span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span>, <span class="kw4">const</span> Foo<span class="sy3">&amp;</span><span class="br0">)</span><span class="sy4">;</span>
    <span class="co1">// 注意：这依赖于声明中的模板实参推导</span>
    <span class="co1">// 亦可以 operator&lt;&lt; &lt;T&gt; 指定模板实参</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="co1">// 定义</span>
<span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> T<span class="sy1">&gt;</span>
<a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> os, <span class="kw4">const</span> Foo<span class="sy1">&lt;</span>T<span class="sy1">&gt;</span><span class="sy3">&amp;</span> obj<span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">return</span> os <span class="sy1">&lt;&lt;</span> obj.<span class="me1">data</span><span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    Foo<span class="sy1">&lt;</span><span class="kw4">double</span><span class="sy1">&gt;</span> obj<span class="br0">(</span><span class="nu16">1.23</span><span class="br0">)</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> obj <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p><br> 
</p>
</div>
<h3><span class="mw-headline" id=".E7.A4.BA.E4.BE.8B">示例</span></h3>
<div class="t-example"><p>流插入与提取运算符往往声明为非成员友元</p><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;sstream&gt;</span>
 
<span class="kw1">class</span> MyClass <span class="br0">{</span>
    <span class="kw4">int</span> i<span class="sy4">;</span>
 
    <span class="kw1">friend</span> <a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> out, <span class="kw4">const</span> MyClass<span class="sy3">&amp;</span> o<span class="br0">)</span><span class="sy4">;</span>
    <span class="kw1">friend</span> <a href="../io/basic_istream.html"><span class="kw1727">std::<span class="me2">istream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&gt;&gt;</span><span class="br0">(</span><a href="../io/basic_istream.html"><span class="kw1727">std::<span class="me2">istream</span></span></a><span class="sy3">&amp;</span> in, MyClass<span class="sy3">&amp;</span> o<span class="br0">)</span><span class="sy4">;</span>
 <span class="kw1">public</span><span class="sy4">:</span>
    MyClass<span class="br0">(</span><span class="kw4">int</span> i <span class="sy1">=</span> <span class="nu0">0</span><span class="br0">)</span> <span class="sy4">:</span> i<span class="br0">(</span>i<span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&lt;&lt;</span><span class="br0">(</span><a href="../io/basic_ostream.html"><span class="kw1729">std::<span class="me2">ostream</span></span></a><span class="sy3">&amp;</span> out, <span class="kw4">const</span> MyClass<span class="sy3">&amp;</span> mc<span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">return</span> out <span class="sy1">&lt;&lt;</span> mc.<span class="me1">i</span><span class="sy4">;</span>
<span class="br0">}</span>
 
<a href="../io/basic_istream.html"><span class="kw1727">std::<span class="me2">istream</span></span></a><span class="sy3">&amp;</span> operator<span class="sy1">&gt;&gt;</span><span class="br0">(</span><a href="../io/basic_istream.html"><span class="kw1727">std::<span class="me2">istream</span></span></a><span class="sy3">&amp;</span> in, MyClass<span class="sy3">&amp;</span> mc<span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">return</span> in <span class="sy1">&gt;&gt;</span> mc.<span class="me1">i</span><span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    MyClass mc<span class="br0">(</span><span class="nu0">7</span><span class="br0">)</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> mc <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    <a href="../io/basic_istringstream.html"><span class="kw1735">std::<span class="me2">istringstream</span></span></a><span class="br0">(</span><span class="st0">"100"</span><span class="br0">)</span> <span class="sy1">&gt;&gt;</span> mc<span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> mc <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">7
100</pre></div></div> 
</div>
<h3><span class="mw-headline" id=".E7.BC.BA.E9.99.B7.E6.8A.A5.E5.91.8A">缺陷报告</span></h3>
<p>下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
</p>
<table class="dsctable" style="font-size:0.8em">
<tr>
<th> DR
</th>
<th> 应用于
</th>
<th> 出版时的行为
</th>
<th> 正确行为
</th></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.cmeerw.net/cwg/issue45">CWG 45</a>
</td>
<td> C++98
</td>
<td> <code>T</code> 的友元类的嵌套类的成员对 <code>T</code> 没有特殊访问权
</td>
<td> 嵌套类拥有和外围类相同的访问权
</td></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.cmeerw.net/cwg/issue500">CWG 500</a>
</td>
<td> C++98
</td>
<td> <code>T</code> 的友元类不能继承自 <code>T</code> 的私有与受保护成员，但其嵌套类可以
</td>
<td> 都可以继承自此种成员
</td></tr></table>
<h3><span class="mw-headline" id=".E5.BC.95.E7.94.A8">引用</span></h3>
<div class="t-ref-std-c++11">
<ul><li> C++11 standard (ISO/IEC 14882:2011): 
</li></ul>
<dl><dd><ul><li> 11.3 Friends [class.friend]
</li></ul>
</dd></dl>
<dl><dd><ul><li> 14.5.4 Friends [temp.friend]
</li></ul>
</dd></dl>
</div>
<div class="t-ref-std-c++98">
<ul><li> C++98 standard (ISO/IEC 14882:1998): 
</li></ul>
<dl><dd><ul><li> 11.3 Friends [class.friend]
</li></ul>
</dd></dl>
<dl><dd><ul><li> 14.5.3 Friends [temp.friend]
</li></ul>
</dd></dl>
</div>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<table class="t-dsc-begin">

<tr class="t-dsc">
<td colspan="2">  <a href="class.html" title="cpp/language/class">类声明</a>
</td></tr>

<tr class="t-dsc">
<td colspan="2">  <a href="access.html" title="cpp/language/access">访问说明符</a>
</td></tr>
</table>

<!-- 
NewPP limit report
Preprocessor visited node count: 2335/1000000
Preprocessor generated node count: 6316/1000000
Post‐expand include size: 50672/2097152 bytes
Template argument size: 15918/2097152 bytes
Highest expansion depth: 14/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:2716-0!*!0!!zh!*!zh!* and timestamp 20200223160447 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/friend&amp;oldid=64193">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/friend&amp;oldid=64193</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/friend">Online version</a></li><li>Offline version retrieved 2020-03-14 18:00.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2020年1月28日 (星期二) 23:27。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过15,381次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 1.500 secs. -->
	</body>
<!-- Cached 20200223160447 -->
</html>